/*
 * Copyright (c) 2022-2023 cetcclout Co., Ltd All rights reserved.
 * Sensor Adapter is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package com.cetccloud.cimp.adapter.handler.hj212;

import cn.hutool.core.io.BufferUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;

import com.cetccloud.cimp.adapter.datasource.sqldb.service.impl.EnvRuleHj212ServiceImpl;
import com.cetccloud.cimp.adapter.handler.abstracts.AbstractParserHandler;
import com.cetccloud.cimp.adapter.handler.hj212.parse.EnvHJ212Parse;
import com.cetccloud.cimp.common.util.SensorStringUtils;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.nio.Buffer;

/**
 * @author
 * @apiNote 报文数据转换
 * @date 2023/3/3 19:20
 */
@Component("hj212ParserHandler")
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class HJ212ParserHandler extends AbstractParserHandler {
    private final static InternalLogger logger = InternalLoggerFactory.getInstance(HJ212ParserHandler.class);

    @Autowired
    private EnvRuleHj212ServiceImpl envRuleHj212Service;

    //协议转换配置信息
    private static JSONArray localConfig = new JSONArray();
    
    /**
     * 初始化报文转换配置
     */
    @Override
    public void init(String tableName){
        localConfig = envRuleHj212Service.getConfig(tableName);
        logger.info("当前服务配置：{}",JSONUtil.toJsonStr(localConfig));
    }

    /**
     * 设备报文转换为系统报文
     */
    @Override
    public Buffer unpack(Buffer buffer, String dtuId) {
        String data = new String((byte[]) buffer.array());
        logger.info("报文数据析：{}", data);

        JSON parseData = null;
        if (SensorStringUtils.startsWith(data, "##")){
            logger.info("环境监测数据！！！！！");
            data = SensorStringUtils.endsWith(data, "\r\n") ? data : data+"\r\n";
            //数据转换到JSON
            parseData = EnvHJ212Parse.envDataParse(data,localConfig);
            //标记数据所属平台类型
            this.dataType = "ENV_DATA";

        }
        return ObjectUtil.isEmpty(parseData) ? null : BufferUtil.createUtf8(JSONUtil.toJsonStr(parseData));
    }

    /**
     * 系统报文转换为设备报文
     */
    @Override
    public Buffer pack(Buffer buffer, String dtuId) {
        return null;
    }
}
